﻿using System;
using System.Diagnostics;
using System.Threading;
using System.Windows;
using System.Windows.Threading;
using KsWare.Breconium.Core;

namespace Ksx.KoCTool {

	/// <summary> Interaction logic for App.xaml
	/// </summary>
	public partial class App : Application {
		private BreconiumServer mServer;

		public BreconiumServer Server { get { return mServer; } }

		protected override void OnStartup(StartupEventArgs e) {
			base.OnStartup(e);
			mServer = BreconiumServer.Default;
			mServer.SessionStart+=ServerOnSessionStart;
			mServer.Start(new[] {"http://127.0.0.1:33333/"});
		}

		protected override void OnExit(ExitEventArgs e) {
			base.OnExit(e);
			BreconiumServer.Default.Stop();
		}

		private void ServerOnSessionStart(object sender, SessionEventArgs e) { 
			App.Trace("ServerOnSessionStart "+"\r\n\tLocation: "+e.Session.Location);
		}

		public static void SetStatus(string s) { 
			((MainWindow)Application.Current.MainWindow).mStatusbarText.Text=s;
			DoEvents();
		}
		public static void DoEvents() {Application.Current.Dispatcher.Invoke(DispatcherPriority.Background,new Action(delegate { }));}

		#region Trace
		internal static void Trace(string message) {Trace("{0}",message);}

		internal static void Trace(string format, params object[] args) {
			var message = ((args == null || args.Length == 0) ? format : string.Format(string.Format(format, args)));
			message = string.Format("{0:HH:mm:ss.fff} {1,4} {2}", DateTime.Now, Thread.CurrentThread.ManagedThreadId, message);
			System.Diagnostics.Trace.WriteLine(message);
		}
		#endregion
	}
}
